package com.example.reschain;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {

    private static final int THREAD_COUNT_NUM = 7;

    private static final CountDownLatch latch = new CountDownLatch(THREAD_COUNT_NUM);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < THREAD_COUNT_NUM; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "执行");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //每个线程执行完毕，都把计数器减1
                latch.countDown();
            }, "Thread" + i).start();
        }

        // CountDownLatch.await()阻塞主函数。
        // 那么，主函数需要等到 latch.countDown()被调用七次后，方可恢复执行
        latch.await();
        System.out.println("主函数阻塞结束");


    }
}